<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>4-7-8 呼吸法</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<body class="bg-gradient-to-br from-indigo-100 to-blue-200 min-h-screen flex items-center justify-center">
  <div class="bg-white shadow-2xl rounded-2xl p-8 max-w-md w-full text-center" x-data="breathingTool()">
    <h1 class="text-3xl font-bold mb-6 text-gray-800">4-7-8 呼吸法</h1>
    <div class="text-xl text-gray-600 mb-2" x-text="phase"></div>
    <div class="text-6xl font-bold text-indigo-600 mb-6" x-text="timer"></div>
    <div class="space-x-4">
      <button @click="startBreathing" class="px-6 py-2 bg-indigo-500 text-white rounded-full hover:bg-indigo-600">开始</button>
      <button @click="stopBreathing" class="px-6 py-2 bg-gray-300 text-gray-700 rounded-full hover:bg-gray-400">停止</button>
    </div>
  </div>

  <script>
    function breathingTool() {
      return {
        phase: '点击开始',
        timer: '--',
        interval: null,
        currentPhase: 0,
        count: 0,
        totalRounds: 4,
        cycle: [
          { phase: "吸气", time: 4 },
          { phase: "屏气", time: 7 },
          { phase: "呼气", time: 8 }
        ],
        startBreathing() {
          if (this.interval) return;
          this.currentPhase = 0;
          this.count = 0;
          this.runPhase();
        },
        runPhase() {
          if (this.count >= this.totalRounds * this.cycle.length) {
            this.phase = "完成！";
            this.timer = "✓";
            this.interval = null;
            return;
          }

          const phaseData = this.cycle[this.currentPhase % this.cycle.length];
          let timeLeft = phaseData.time;
          this.phase = phaseData.phase;
          this.timer = timeLeft;

          this.interval = setInterval(() => {
            timeLeft--;
            if (timeLeft <= 0) {
              clearInterval(this.interval);
              this.interval = null;
              this.currentPhase++;
              this.count++;
              this.runPhase();
            } else {
              this.timer = timeLeft;
            }
          }, 1000);
        },
        stopBreathing() {
          clearInterval(this.interval);
          this.interval = null;
          this.phase = "已停止";
          this.timer = "--";
        }
      }
    }
  </script>
</body>
</html>
